//
//  SupplierCategoryManager.m
//  takeout
//
//  Created by Derekc on 12-2-26.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SupplierCategoryManager.h"
#import "ResolveXML.h"
#import "Constants.h"

@implementation SupplierCategoryManager

-(NSArray *)getAllSupplierCategories{
    return self.getAllSupplierCategoriesFromXML;
}
//从请求返回的xml中取数据
-(NSArray *)getAllSupplierCategoriesFromXML{
    NSString *URIString = [[NSString alloc]initWithFormat:SERVICE_DOMAIN, SERVICE_ALL_SUPPLIERS_CATEGORIES];
    NSURL *url = [[NSURL alloc] initWithString:[URIString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [NSMutableURLRequest new];    
    [request setURL:url];    
    [request setHTTPMethod:@"GET"]; 
    NSHTTPURLResponse* response;    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
    NSString* responseXMLResult=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString: responseXMLResult options:0 error:&error];
    
    NSArray *children = [doc.rootElement children]; 
    NSMutableArray *result = nil;
    for (GDataXMLElement *element in children) {
        if ([element isKindOfClass:[GDataXMLElement class]]) {
            SupplierCategory *supplierCategory = [[SupplierCategory alloc] init];
            //id 为第1个子节点，name第2个子节点
            supplierCategory.supplierCategoryId = [[[element childAtIndex:0] stringValue] intValue];
            supplierCategory.supplierCategoryName = [[element childAtIndex:1] stringValue];
            if (result == nil) {
                result = [NSMutableArray arrayWithObject:supplierCategory];
            }else{
                [result addObject:supplierCategory];
            }
        }
    } 

    return result;
}
@end
